package pb;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by gamy on 2017/8/3.
 */
public class PBMessage {
    private String name;
    private boolean hasTable;
    private ArrayList<PBField> fields;
    private String lineStr;

    private static final String PB_MESSAGE = "message";
    private static final String MESSAGE_PATTEN = new String("message\\s+([a-zA-Z]+)");
    private static final String SQL_TABLE = "sql_table";


    public PBMessage(String lineStr) {
        this.lineStr = lineStr;
        Matcher matcher = Pattern.compile(MESSAGE_PATTEN).matcher(lineStr);
        if (matcher.find()){
            this.name = matcher.group(1);
        }
        if (lineStr.contains(SQL_TABLE)) {
            this.hasTable = true;
        }
        this.fields = new ArrayList<PBField>();
    }

    public static boolean isMessageLineString(String lineStr) {
        Matcher matcher = Pattern.compile(MESSAGE_PATTEN).matcher(lineStr);
        return matcher.find();
    }

    public void addField(PBField field){
        this.fields.add(field);
    }


    public String getSqlStament()
    {
        String st = "CREATE TABLE IF NOT EXISTS " + this.name.substring(0)+"\n(\n";
        int i = 0;
        for (PBField field : this.fields){
            st += field.getSqlStament();
            if (i != this.fields.size() - 1){
                st+=",\n";
            }else{
                st+="\n);";
            }
            i ++;
        }
        return st;
    }

    @Override
    public String toString() {
        return this.getSqlStament();
        /*
        return "PBMessage{" +
                "name='" + name + '\'' +
                ", hasTable=" + hasTable +
                ", fields=" + fields +
                '}';
                */
    }
}
